package com.cbgolf.oa.util;

import static android.widget.Toast.makeText;
import static com.cbgolf.oa.util.ErrorUtil.NETERROR;
import static com.cbgolf.oa.util.ErrorUtil.NODATA;
import static com.cbgolf.oa.util.ErrorUtil.NONET;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.cbgolf.oa.R;
import com.cbgolf.oa.activity.publiz.LoginActivity;
import com.cbgolf.oa.app.App;
import com.cbgolf.oa.app.AppManager;
import com.cbgolf.oa.inteface.IAsynTask;
import com.cbgolf.oa.user.User;
import com.cbgolf.oa.user.UserData;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;


public class Util {



    public static void showNoNet() {
        show(NONET);
    }

    public static void showNetError() {
        show(NETERROR);
    }

    public static void showNoData() {
        show(NODATA);
    }

    public static void checkNet() {
        if (!isNetWorkConnected()) {
            showNoNet();
        }
    }
    public static boolean isEquals(Object o1, Object o2) {
        return null != o1 && null != o2 && o1.toString().equals(o2.toString());
    }
    public static boolean isEqualsIgnoreCase(Object o1, Object o2) {
        return null != o1 && null != o2 && o1.toString().equalsIgnoreCase(o2.toString());
    }

    public static String checkNull(String obj) {
        return isNull(obj) ? "" : String.valueOf(obj);
    }
    public static boolean listIsNull(List<? extends Object> list) {
        return null == list || list.size() == 0;
    }

    public static void showTokenBad() {
        if (null != UserData.getUser()) {
            DbManager db = x.getDb(App.getDaoConfig());
            try {
                db.delete(User.class);
                db.dropTable(User.class);
            } catch (DbException e) {
                e.printStackTrace();
            }
            UserData.setUser(null);
        }
        Intent intent = new Intent(App.getContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getContext().startActivity(intent);
        Activity act = AppManager.getNewInstance().getStaskTopActivity();
        if (null != act && !act.isFinishing()) {
            act.overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
        }
//        show("登录信息过期");
    }


    public static void show(String msg, Activity activity) {
        Toast t = makeText(activity, msg, Toast.LENGTH_SHORT);
        t.show();
    }

    public static void show(String msg) {
        Toast mToast = Toast.makeText(App.getContext(), msg, Toast.LENGTH_SHORT);
        // t.setGravity(Gravity.TOP, 0, 0);
        mToast.show();
    }

    public static boolean isNull(Object obj) {
        return null == obj || "".equalsIgnoreCase(obj.toString());
    }

    //特殊字符
    public static boolean hasSpChar(String str) {

        String limitEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(limitEx);
        Matcher m = pattern.matcher(str);
//        if(m.find()){
//            return true;
//        }
        return m.find();
    }


    public static boolean isNetWorkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) App.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null == connectivityManager) {
            return false;
        }
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return null != networkInfo && networkInfo.isConnected();
    }

    public static void asynTask(final IAsynTask task) {
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Bundle data = msg.getData();
                String dataType = data.getString("IAsynTaskResult");
                Serializable ser = data.getSerializable("IAsynTaskRunData");
                if ("success".equals(dataType))
                    task.updateUI(ser);
                else if ("error".equals(dataType)) {
                    // Util.show("网络异常，请稍候再试！", App.getContext());
                    System.err.println("--------------异步任务错误！-------------");
                    if (null == ser)
                        Log.e("Util异步任务错误！", ((Throwable) ser) + "");
                    else
                        ((Throwable) ser).printStackTrace();
                } else {
                    task.updateUI(null);
                }
            }
        };

        new Thread(new Runnable() {
            public void run() {
                Message msg = new Message();
                Bundle data = new Bundle();
                try {
                    data.putSerializable("IAsynTaskRunData", task.Run());
                    data.putString("IAsynTaskResult", "success");
                } catch (Throwable e) {
                    data.putSerializable("IAsynTaskRunData", e);
                    data.putString("IAsynTaskResult", "error");
                }
                msg.setData(data);
                handler.sendMessage(msg);
            }
        }).start();
    }


    public static boolean isInt(Object obj) {
        if (!isNull(obj)) {
            return obj.toString().matches("^[-]?\\d+$");
        }
        return false;
    }

    public static boolean isLong(Object obj) {
        if (!isNull(obj)) {
            try {
                Long l = Long.parseLong(obj.toString());
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    public static boolean isDouble(Object obj) {
        if (!isNull(obj)) {
            return obj.toString().matches("^\\d+(\\.[\\d]+)?$");
        }
        return false;
    }

    public static boolean isPhone(String phonenumber) {
        Pattern pa = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        Matcher ma = pa.matcher(phonenumber);
        return ma.matches();
//        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(14[57])|(17[0])|(17[7])|(18[0,0-9]))\\d{8}$");
//        Matcher m = p.matcher(phonenumber);
//        return m.matches();
    }

    public static boolean check(String str, String regex) {
        boolean flag = true;
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 判断是否是银行卡号
     *
     * @param cardId
     * @return
     */
    public static boolean isBankCardNum(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;

    }

    private static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    public static boolean isEmail(String email) {
        Pattern p = Pattern.compile("[a-zA-Z0-9-_]+@+[a-zA-Z0-9]+.+[a-zA-Z0-9]");
        Matcher ma = p.matcher(email);
        return ma.matches();
    }

    public static boolean isQQ(String QQ) {
        String regex = "^[1-9][0-9]{4,} $";
        return check(QQ, regex);
    }

    public static boolean isShenFenZhengNum(String num) {
        String regx = "[0-9]{17}x";
        String regx2 = "[0-9]{17}X";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return num.matches(regx) || num.matches(reg1) || num.matches(regex) || num.matches(regx2);
    }

    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        /*
         * 可接受的电话格式有：
		 */
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
        /*
         * 可接受的电话格式有：
		 */
        String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);

        Pattern pattern2 = Pattern.compile(expression2);
        Matcher matcher2 = pattern2.matcher(inputStr);
        if (matcher.matches() || matcher2.matches()) {
            isValid = true;
        }
        return isValid;
    }

//	// 验证号码 手机号 固话均可
//	public static boolean isPhoneOrTelNumber(String phoneNumber) {
//		boolean isValid = false;
//
//		String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
//		CharSequence inputStr = phoneNumber;
//
//		Pattern pattern = Pattern.compile(expression);
//
//		Matcher matcher = pattern.matcher(inputStr);
//
//		if (matcher.matches()) {
//			isValid = true;
//		}
//
//		return isValid;
//
//	}

    public static long toSeconds(long date) {
        return date / 1000L;
    }

    public static long toMinutes(long date) {
        return toSeconds(date) / 60L;
    }

    public static long toHours(long date) {
        return toMinutes(date) / 60L;
    }

    public static long toDays(long date) {
        return toHours(date) / 24L;
    }

    public static long toMonths(long date) {
        return toDays(date) / 30L;
    }

    public static long toYears(long date) {
        return toMonths(date) / 365L;
    }

    //    1、判断是否安装
    /*
    * check the app is installed
    */
    public static boolean isInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            //System.out.println("没有安装");
            return false;
        } else {
            //System.out.println("已经安装");
            return true;
        }
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                Log.e("pn =", pn + "");
                if (pn.equalsIgnoreCase("com.tencent.qqlite") ||
                        pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isAppAlive(Context context, String pageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(pageName) || info.baseActivity.getPackageName().equals(pageName)) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }

    public static boolean isLarge() {
        boolean isLarge = false;
        try {
            isLarge = App.getContext().getResources().getBoolean(R.bool.islarge);
        } catch (Exception e) {

        }
        return isLarge;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOpenGPS(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }
    public static void hideKeyboard(Activity context) {
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).
            hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void showInput(final EditText et) {
        Observable.timer(10, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(aLong -> {
                InputMethodManager inputManager =
                    (InputMethodManager) et.getContext().
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(et, 0);
            });
    }

    public static void callPhone(Activity act, String phone) {
        if (Util.isNull(phone)) {
            show("很抱歉，电话号码为空");
            return;
        }
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            act.startActivity(intent);
        } catch (Exception e) {

        }
    }


}
